<?php namespace Home\Controller; 
use Hdphp\Controller\Controller;
//订单控制器
class OrdersController extends CommonController{
	//构造函数
	public function __init()
	{
		parent::__init();
	}
	
 	//订单信息确认
    public function index(){
		//检查用户是否登陆
		if(!empty($_SESSION['user_id'])){

			//获取购物车商品信息
			$goods = $this->goodsList();

			//清除未知的值
			unset($goods['undefined']);

			//实例化用户表
			$userModel = new \Common\Model\User;
			$user_id = $_SESSION['user_id'];
			//p($user_id);

			//根据用户查询地址信息
			$userAddress = $userModel->join('address','user_user_id','=','user_id')
									 ->where("user_id={$user_id} and isDefault=1")
								     ->field('address.*')
									 ->find();

			//P($userAddress);
			if($userAddress['addr_id']){
				$_SESSION['addr_id'] = $userAddress['addr_id'];	
			}else{
				$this->error = '地址不存在！';
			}
			//分配变量
					
			View::with('list',$userAddress);
			View::with('user_id',$user_id);
			
			//获得商品总价格
	  		$TotalPrice = Cart::getTotalPrice(); 
			 View::with('TotalPrice',$TotalPrice);
	        //统计购物车中的商品数量
			$TotalNums = Cart::getTotalNums(); 
			View::with('TotalNums',$TotalNums);
	        //获得定单号
			$OrderId = Cart::getOrderId();
            View::with('OrderId',$OrderId);
			
			View::with('goods',$goods);
			
			View::make();

		}else{
			//没有登陆
			echo json_encode(false);
		}

       // View::make();
    }
	
	
	//修改收货信息
	public function editAddress(){

		//实例化地址表
		$addressModel = new \Common\Model\Address;
		//接收数据
		$data = Q("post.");
		
		//根据主键判断是否有默认地址
		if(!$data['addr_id']){

			//判断之前有多少个地址
			$user = $_SESSION['user'];
			$addressNum = $addressModel->where('userId='.$user['userId'])->count();

			if($addressNum > 3){
				echo json_encode('num');
			}

			if(!empty($_SESSION['addr_id'])){

				$default['isDefault'] = 0;
				//修改旧默认地址
				$addressModel->where('addr_id='.$_SESSION['addr_id'])->save($default);
			}

			//添加默认地址
			$addressId = $addressModel->data($data)->add();

			$_SESSION['addr_id'] = $addressId;

			echo json_encode($addressId);
			
		}else {
			//更新
			$list = $address->save($data);

			//判断是否更新成功
			if($list === false){
				$this->ajaxReturn('false');
				echo json_encode(false);

			}


		}

	}
	
	//删除收货人信息
	public function delAddress(){

		//接收数据
		$data = Q("post.");
		
		//实例化地址表
		$addressModel = new \Common\Model\Address;

		//删除
		$list = $addressModel->where($data)->delete();

		//判断删除是否成功
		if($list === false){
			echo json_encode(false);exit;
		}else{
			echo json_encode($list);
		}


	}
	
	
	//订单提交成功
	public function orderSubmit(){
//  dump($_SESSION['cart']);
		//判断用户有没有登录
		if(!empty($_SESSION['user'])) {
			if(!empty($_SESSION['cart'])){
				//实例化表
				$addressModel = new \Common\Model\Address;
				//实例化订单表
				$orderModel = new \Common\Model\Order;
				//实例化订单列表
				$orderModel = new \Common\Model\Order_detail;
				//实例化商品表
				$goodsModel = new \Common\Model\Goods;
				//实例化用户表
				$userModel = new \Common\Model\User;
				
				//查询
				$addressList = $addressModel->field('receiver,phone_tel,phone_mob,address,email,payment,addressbie')
											->where('addr_id='.$_SESSION['addr_id'])
											->find();

				//取出session中的值
				//订单
				$data = array();
				foreach($addressList as $key=>$val) {

					if($key == payment) {
						$payment = $val;
					}else{
						$data[$key] = $val;
					}
					
				}

				$data['user_id'] = $_SESSION['user']['user_id'];
				$data['add_time'] = time();//订购时间（生成时间）

				//生成订单数据,返回订单号
				$order_id = $orderModel->data($data)->add();

				//订单详情
				foreach($_SESSION['cart'] as $k=>$v) {

					//过滤不是商品的键值
					if(is_int($k)) {

						//查询商品编号
						$goodsList = $goodsModel
							->where('goods.goods_id='.$k)
							->join('orders','goods_goods_id','=','goods_id')
							->find();

						$detailData['goods_id'] = $goodsList['goods_id'];
						$detailData['order_id'] = $order_id;
						$detailData['amount'] = $v['num'];
						$detailData['price'] = $goodsList['price2'];
						$otherInfo = $v['num'] * $goodsList['price2'];

						//购买数量，减去库存						
						$goodsModel->where('goods_id='.$goodsList['goods_id'])->setInc('saleNum',$v['num']);
						$goodsModel->where('goods_id='.$goodsList['goods_id'])->setDec('amount',$v['num']);

						$detail->data($detailData)->add();

					}else{

						continue;
					}
				}

				//总价格
				$tprice = $_SESSION['cart']['tprice'];
		
				//分配变量
				View::with('payment',$addressList['payment']);
				View::with('order_id',$order_id);
				View::with('tprice',$tprice);

				//加载模板
				View::make();
				
				//订单成功后清除session中购买的商品信息
				//unset($_SESSION['cart']);
			   //unset($_SESSION['addressId']);

			}else{

				View::make();
			}

		}else{

			View::make('Login/index');

		}

	}

	//获取购物车内 即 遍历session里商品
	private function goodsList(){
		//p($_SESSION['cart']['goods']);
		//实例化商品表
		$goodsModel = new \Common\Model\Goods;
		//定义数组存放值
		$list = array();
		//判断session中有没有存放商品
		if(!empty($_SESSION['cart']['goods'])){
			//把遍历的数据存放到变量中
			foreach($_SESSION['cart']['goods'] as $k=>$v){
				//p($k);// $k 是当前 商品的 SID -- b3868a26
				//p($v);exit;
				
				//p($v['id']);exit;
				//过滤掉不是商品的值 
				//判断变量类型是否为整数类型
				if(is_int($v['id'])){	
					$list[$k] = $goodsModel->where('goods_id='.$v['id'])->find();
				}else{
					$list[$k] = $v;
					continue;
				}
			}
		}
		//p($list);
		return $list;
	}


	
}